<?php

/**
 * Encode an array
 *
 * @param array &$var
 */
function urlencode_array(&$var)
{
	if (is_array($var)) {
		foreach (array_keys($var) as $k) {
			$var[$k] = urlencode($var[$k]);
		}
	}
}

/**
 * Function to redirect a user to certain pages
 */
function redirect_entete($url) {
	header("Location: " . APPLICATION_URL . $url);
	exit();
}

/**
 * Vérifier si la page courente est le page qu'on veut comparer
 */
function is_page_courante($page) {
	//return ('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] == APPLICATION_URL . '/' . $page);
	$controller = DRX::load("controller");
	return $controller == $page;
}

// check login and use SHA1 to encode password
function connecter_utilisateur($login, $pwd, $project = USER_PROJECT_ACCESS_ALLOWED_GALLERY) {

	$acces = new Login();

	$acces->whereAdd("EMAIL = '" . mysql_real_escape_string($login) . "'");
	$acces->whereAdd("PASSWORD = '" . sha1(mysql_real_escape_string($pwd)) . "'");


	$acces->DISABLED = 0;
	$acces->find();
   
	if ($acces->fetch())
		return $acces;

	return null;

}

// check login by ID
function connecter_utilisateur_byID($id)
{
	$acces = new Login();

	$acces->whereAdd("ID = " . $id);

	$acces->DISABLED = 0;
	$acces->find();

	if ($acces->fetch())
		return $acces;

	return null;
}

function get_url_request($main_url) {
	$request = array_merge($_POST, $_GET);
	return get_link_from_array($main_url, $request);
}

function get_link_from_array($base_url, $request) {
	$url = $base_url;
	$i = 0;
	if (sizeof($request) == 0)
		$url .= "?";

	foreach($request as $key => $value) {
		if ($i == 0) {
			$url .= "?" . $key . "=" . $value;
			$i++;
			continue;
		}
		$url .= "&" . $key . "=" . $value;
	}
	return $url;
}

function set_link_retour($link, $name_obj) {
	$_SESSION[$name_obj . "_link_retour"] = get_url_request($link);
}

function get_link_retour_4_redirect($name_obj,$default = "") {
	if (isset($_SESSION[$name_obj . "_link_retour"]))
		return str_replace("&amp;", "&", $_SESSION[$name_obj . "_link_retour"]);
	return $default;
}

function date_to_date_sql($date_convert) {

	$pos = strpos($date_convert, '/');
	if ($pos === false)
		return $date_convert;

	list($day, $month, $year) = explode("/", $date_convert);

	if (($year == "1970") && ($month == "01" || $month == "1") && ($day == "01" || $day == "1"))
		return "1970-01-01";

	if (!is_numeric($day) || !is_numeric($month) || !is_numeric($year))
		return "";

	if ($day < 1 || $day > 31)
		return "";
	if ($month < 1 || $month > 12)
		return "";
	if ($year < 0 || $year > 10000)
		return "";

	//if (check_date($date_convert))
	return date("Y-m-d", mktime(0, 0, 0, intval($month), intval($day), intval($year)));

}

function date_sql_to_date($date_convert) {
	//$date_convert = "yyyy-mm-dd";
	$pos = strpos($date_convert, '-');
	if ($pos === false)
		return $date_convert;

	list($year, $month, $day) = explode("-", $date_convert);
	return $day . "/" . $month . "/" . $year;
}

function check_date($date) {
	$date = trim($date);
	if (empty($date)) {
		return false;
	}

	$date_array = explode("/", $date);
	$day = isset($date_array[0]) ? $date_array[0] : - 1;
	$month = isset($date_array[1]) ? $date_array[1] : - 1;
	$year = isset($date_array[2]) ? $date_array[2] : - 1;

	if (!is_numeric($day) || !is_numeric($month) || !is_numeric($year))
		return FALSE;

	if ($day < 1 || $day > 31)
		return false;
	if ($month < 1 || $month > 12)
		return false;
	if ($year < 0 || $year > 10000)
		return false;

	if (checkdate($month, $day, $year)) {
		return true;
	}
	else {
		return false;
	}
}

function check_debut($debut) {
	return (strtotime(date_to_date_sql($debut) . " " . date("H:i:s")) >= time());
}

/**
 * Check if the email string is valided. That is the email that has:
 * Domain name rule: - Use only letters, numbers, or hyphen ('-')
 * 					 - Can not begin or end with a hyphen
 * 					 - Must have less than 63 characters, not include extension
 *
 * @param string $email
 * @return true if $email is a valid email; false otherwise
 */
function checkEmailValide($email)
{
	$patterns = '/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/ix';
	/*$patterns = '/^(.+)'.
				 '[@]'.
				 '([^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\]' .
				 '[-a-z0-9]{0,62}' .
				 '[^-~!@#$%^&*()_+={\\[\\]}:;"\'<,>.?\/\\|\\\\])'.
				 '\.'.
				 '([a-z]{2}'.
				 '|com|net|edu|org'.
				 '|gov|mil|int|biz'.
				 '|pro|info|arpa|aero'.
				 '|coop|name|museum)$/ix';*/

	$FILTER = '"'."\'";
	$email = str_replace(str_split($FILTER), "", $email);

	if(preg_match($patterns,trim($email), $matches)==1)
		return true;
	return false;
}

/**
 * Check whether the url is valid
 *
 * @param unknown_type $url
 * @return unknown
 */
function checkValidUrl($url)
{
	$url = trim($url);
	if (strpos($url,' ') !== false) {
		return false;
	}

	$patterns = '/^http(s)?:\/\/[\w|\-]+(\.[^\.]+)+$/i';

	if(preg_match($patterns,trim($url), $matches)==1)
	{
		return true;
	}
	return false;
}

function getMoisText($mois)
{
	switch($mois) {
		case 1 :
			return _LB_JANVIER;
		case 2 :
			return _LB_FEVRIER;
		case 3 :
			return _LB_MARS;
		case 4 :
			return _LB_AVRIL;
		case 5 :
			return _LB_MAI;
		case 6 :
			return _LB_JUIN;
		case 7 :
			return _LB_JUILLET;
		case 8 :
			return _LB_AOUT;
		case 9 :
			return _LB_SEPTEMBRE;
		case 10 :
			return _LB_OCTOBRE;
		case 11 :
			return _LB_NOVEMBRE;
		case 12 :
			return _LB_DECEMBRE;
	}
}

function url_exists($url) {
	//desactivation du test
	return true;

	$ch = curl_init();
	curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_HEADER, 0);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
	curl_exec ($ch);
	$exists = (curl_errno($ch) == 0);
	curl_close ($ch);
	return $exists;

}

function datediff($interval, $datefrom, $dateto, $using_timestamps = false)
{
  /*
	$interval can be:
	yyyy - Number of full years
	q - Number of full quarters
	m - Number of full months
	y - Difference between day numbers
	  (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
	d - Number of full days
	w - Number of full weekdays
	ww - Number of full weeks
	h - Number of full hours
	n - Number of full minutes
	s - Number of full seconds (default)
  */

  if (!$using_timestamps)
  {
	$datefrom = strtotime($datefrom, 0);
	$dateto = strtotime($dateto, 0);
  }
  $difference = $dateto - $datefrom; // Difference in seconds

  switch($interval) {

	case 'yyyy': // Number of full years

	  $years_difference = round($difference / 31536000);
	  if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
		$years_difference--;
	  }
	  if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
		$years_difference++;
	  }
	  $datediff = $years_difference;
	  break;

	case "q": // Number of full quarters

	  $quarters_difference = round($difference / 8035200);
	  while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
		$months_difference++;
	  }
	  $quarters_difference--;
	  $datediff = $quarters_difference;
	  break;

	case "m": // Number of full months

	  $months_difference = round($difference / 2678400);
	  while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
		$months_difference++;
	  }
	  $months_difference--;
	  $datediff = $months_difference;
	  break;

	case 'y': // Difference between day numbers

	  $datediff = date("z", $dateto) - date("z", $datefrom);
	  break;

	case "d": // Number of full days

	  $datediff = round($difference / 86400);
	  break;

	case "w": // Number of full weekdays

	  $days_difference = round($difference / 86400);
	  $weeks_difference = round($days_difference / 7); // Complete weeks
	  $first_day = date("w", $datefrom);
	  $days_remainder = round($days_difference % 7);
	  $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
	  if ($odd_days > 7) { // Sunday
		$days_remainder--;
	  }
	  if ($odd_days > 6) { // Saturday
		$days_remainder--;
	  }
	  $datediff = ($weeks_difference * 5) + $days_remainder;
	  break;

	case "ww": // Number of full weeks

	  $datediff = round($difference / 604800);
	  break;

	case "h": // Number of full hours

	  $datediff = round($difference / 3600);
	  break;

	case "n": // Number of full minutes

	  $datediff = round($difference / 60);
	  break;

	default: // Number of full seconds (default)

	  $datediff = $difference;
	  break;
  }

  return $datediff;
}

function isBetween($date, $start_date, $end_date)
{

	if(datediff("d", $start_date, $date) >= 0 && datediff("d", $date, $end_date) >= 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

if(!function_exists('cal_days_in_month')) {
function cal_days_in_month($month, $year)
{
	return $month == 2 ? $year % 4 ? 28 : 29 : ($month % 7 % 2 ? 31 : 30);
}
}

function addDay($date, $day, $format = "Y/m/d") {
	$time = strtotime($date);
	return date($format, mktime(0, 0, 0, date("m", $time), $day + date("d", $time), date("y", $time)));
}

function addHour($date, $hour, $format = "Y-m-d H:i:s") {
	$time = strtotime($date);
	return date($format, $time + $hour * 60 * 60);
}

function addMonth($date, $month, $format = "Y/m/d") {
	$time = strtotime($date);
	return date($format, mktime(0, 0, 0, $month + date("m", $time), date("d", $time), date("y", $time)));
}

function dateFormat($date, $format) {
	return date($format, strtotime($date));
}

function format_price($price) {
	return number_format($price, 2);
}

/**
 * Format number for save DB, 2 decimal, save for double field
 *
 * @param unknown_type $number
 * @return formated_number
 */
function format_number_db($number)
{
	// exp: xxxx.xx - 1234.12
	return number_format($number, 2, '.', '');
}

function convertToTextSimple($str) {
	$str = str_replace(" ","",$str);
	$txt = preg_replace('/[^a-zA-Z0-9_]/','',$str);
	return $txt;
}

/**
* Get extension of an image file, based on the mime type
*
* @param string $filename
* @return string
*/
function getImageType($filename)
{
	$image_info = getimagesize($filename);
	$type = $image_info['mime'];
	if ($type == "image/gif")
		return '.gif';
	else if ($type == "image/png")
		return '.png';
	else
		return '.jpg';  //default type is IMAGETYPE_JPEG
}

function textvalid($e)
{
	if (trim($e) == "" || $e == null ||  strlen($e) == 0)
		return false;
	else
		return true;
}

function randomCode($length = 10)
{
  // start with a blank password
  $code = "";

  // define possible characters
  $possible = "0123456789bcdfghjkmnpqrstvwxyz_)(*^%$!";

  // set up a counter
  $i = 0;

  // add random characters to $password until $length is reached
  while ($i < $length) {

	// pick a random character from the possible ones
	$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);

	// we don't want this character if it's already in the password
	if (!strstr($code, $char)) {
	  $code .= $char;
	  $i++;
	}

  }
  // done!
  return $code;

}

function xlsColumn($str)
{
	if(strlen($str) ==1){
		return ord($str) - 65;
	}
	else{
		if(strlen($str)==2){
			$first = $str[0];
			$second = $str[1];
			return (ord($first) - 64)*25 + (ord($second) - 64);
		}
	}
}

function getImageProfile($img) {
	$image_info = getimagesize($img);
	$type_code = -1;

	if ($image_info['mime'] == 'image/gif') {
		$type_code = IMAGE_EXT_GIF;
	} else if ($image_info['mime'] == 'image/jpeg') {
		$type_code = IMAGE_EXT_JPEG;
	} else if ($image_info['mime'] == 'image/png') {
		$type_code = IMAGE_EXT_PNG;
	}

	return array(
		'width' => $image_info[0],
		'height' => $image_info[1],
		'type' => $type_code,
		'size' => filesize($img)
	);
}

/**
 * Convert to BMP image type
 *
 * @param unknown_type $imageSource
 * @param unknown_type $imgStoreAtLocation
 * @param unknown_type $limit_width
 * @param unknown_type $limit_height
 * @return unknown
 */
function convertToBMP($imageSource,$imgStoreAtLocation, $limit_width = null, $limit_height = null)
{
	if (!file_exists($imageSource))
	{
		// default image source when $imageSource doesnt' exist
		$imageSource = IMAGE_NO_IMAGE;
	}

	$arr = explode("/",$imageSource);
	$arr_name = explode(".",$arr[count($arr)-1]);
	$filename = $arr_name[0].".bmp";
	$filetype = $arr_name[1];

	switch ($filetype)
	{
		case "png":
					 $im = imagecreatefrompng($imageSource);
					 break;
	   case "jpg":
	   case "jpeg":
					 $im = imagecreatefromjpeg($imageSource);
					 break;
	   case "gif":
					 $im = imagecreatefromgif($imageSource);
					 break;
	}

	if (!$im) return false;
	$b_w = imagesx($im);
	$b_h = imagesy($im);
	$w = imagesx($im);
	$h = imagesy($im);

	if ($limit_width && $w > $limit_width)
	{
		$percent = $limit_width / $w;
		$w = $limit_width;

		$h = round($h * $percent);
	}

	if ($limit_height && $h > $limit_height)
	{
		$percent = $limit_height / $h;
		$h = $limit_height;

		$w = round($w * $percent);
	}

	$result = '';

	$tmp = imagecreatetruecolor($w, $h);
	imagecopyresampled($tmp, $im, 0, 0, 0, 0, $w, $h, $b_w, $b_h);
	imagedestroy($im);
	$im = & $tmp;

	$biBPLine = $w * 3;
	$biStride = ($biBPLine + 3) & ~3;
	$biSizeImage = $biStride * $h;
	$bfOffBits = 54;
	$bfSize = $bfOffBits + $biSizeImage;

	$result .= substr('BM', 0, 2);
	$result .=  pack ('VvvV', $bfSize, 0, 0, $bfOffBits);
	$result .= pack ('VVVvvVVVVVV', 40, $w, $h, 1, 24, 0, $biSizeImage, 0, 0, 0, 0);

	$numpad = $biStride - $biBPLine;
	for ($y = $h - 1; $y >= 0; --$y){
		  for ($x = 0; $x < $w; ++$x) {
				 $col = imagecolorat ($im, $x, $y);
				 $result .=  substr(pack ('V', $col), 0, 3);
		  }
		  for ($i = 0; $i < $numpad; ++$i)
				  $result .= pack ('C', 0);
	}

	if($filename==""){
	   echo $result;
	}
	else
	{
	   $file = fopen($imgStoreAtLocation.$filename, "wb");
	   fwrite($file, $result);
	   fclose($file);
	}

	return $filename;
}

/**
 * Replace accented characters in a string by the corresponding non-accented characters
 *
 * @param $chaine A string
 * @return A corresponding string with non-accented characters
 */
function sans_accent($chaine) {
	  return strtr($chaine,
	  utf8_decode('ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ'),
	  'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
}

function convertDateToDisplayStyle($date, $french_type = true)
	{
		if( preg_match('/[\/-]/', $date) )
		{
		if ($date == '') return '';
		list($year, $month, $day) = preg_split('/[\/-]/', $date);
		//echo "$year, $month, $day";
		//exit();
		$tmp_date = mktime(0, 0, 0, intval($month) , intval($day) , intval($year));
		//echo "$tmp_date";
		//exit();
		}
		else
		{
			$tmp_date = $date;
		}

		if ($french_type)
		{
			return date('d/m/Y', $tmp_date);

		}
		return date('m/d/Y', $tmp_date);

	}
function status2Text($status){
    switch ($status){
        case 0:
            return _LB_WAITING_FOR_APPROVE;
            break;
        case 1:
            return _LB_APPROVED;
            break;
        case 2:
            return _LB_REJECTED;
            break;
    }
}